package com.kaifamiao.reqeust;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Iterator;

@WebServlet("/plain")
public class PlainServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding( "UTF-8" );
        response.setCharacterEncoding( "UTF-8" );
        response.setContentType( "text/html; charset=UTF-8" );
        PrintWriter out = response.getWriter();

        // 获取请求方式(来自HTTP请求的请求行)
        String method = request.getMethod();
        // 获取请求头中`content-type`字段的值
        String contentType = request.getHeader( "content-type" );

        if( "POST".equals( method ) && "text/plain".equals( contentType ) ) {
            BufferedReader br = request.getReader();
            String s ;
            while ( ( s = br.readLine() ) != null ) {
                System.out.println(s);
                String[] arr = s.split( "=" );
                out.printf( "<p>%s: %s</p>\r\n", arr[0], arr[1] );
            }
            return;
        }

        out.println( "<p>不是用POST方式提交了`text/plain`数据</p>" );

    }

}
